﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Read.Application.Excused
{
    public class GetLeaderCommandHandler : IRequestHandler<GetLeaderCommand, APIResult<T_User>>
    {
        private readonly IBaseRepository<T_User> userRepository;
        private readonly IBaseRepository<T_UserRole> urRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<T_Role> roleRepository;
        public GetLeaderCommandHandler(IBaseRepository<T_User> userRepository, IBaseRepository<T_UserRole> urRepository, IBaseRepository<T_Role> roleRepository, IMapper mapper)
        {
            this.userRepository = userRepository;
            this.urRepository = urRepository;
            this.roleRepository = roleRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<T_User>> Handle(GetLeaderCommand request, CancellationToken cancellationToken)
        {
            APIResult<T_User> result = new APIResult<T_User>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            var ridList = request.RidList.Split(",").Select(x => Convert.ToInt32(x));
            List<T_UserRole> userRoles = new List<T_UserRole>();
            int userID = 0;
            //获取当前部门所有用户Id
            var userList = userRepository.GetAll().Where(p => p.DepartMentId == request.DepartId).Select(x => x.Id);
            foreach (var item in userList)
            {
                var urList = urRepository.GetAll().Where(x => x.Uid == item);
                userRoles.AddRange(urList);
            }
            userID = userRoles.FirstOrDefault(x => x.Rid == 11)!.Uid;


            result.Data = userRepository.GetAll().FirstOrDefault(x => x.Id == userID)!;
            return Task.FromResult(result);
        }
    }
}
